// session操作
export const session = {
    set(key:string, value:any) {
        if (typeof value == 'object') {
            value = JSON.stringify(value);
        }
        sessionStorage.setItem(key, value);
    },
    get(key:string) {
        var value = sessionStorage.getItem(key);
        if (value) {
            if (value.charAt(0) == '{' || value.charAt(0) == '[') {
                return JSON.parse(value);
            }
        }
        return value;
    },
    remove(key:string) {
        sessionStorage.removeItem(key);
    }
}

// 本地存储
export const storage = {
    set(key:string, value:any) {
        if (typeof value == 'object') {
            value = JSON.stringify(value);
        }
        localStorage.setItem(key, value);
    },
    get(key:string) {
        var value = localStorage.getItem(key);
        if (value) {
            if (value.charAt(0) == '{' || value.charAt(0) == '[') {
                return JSON.parse(value);
            }
        }
        return value;
    },
    remove(key:string) {
        localStorage.removeItem(key);
    }
}

// cookie操作
export const cookie = {
    set(key:string, value:any, day:number) {
        if (typeof value == 'object') {
            value = JSON.stringify(value);
        }

        var date = new Date();
        var expiresDays = day | 1;
        date.setTime(date.getTime() + expiresDays * 24 * 3600 * 1000);
        document.cookie = key + "=" + value + ";expires=" + date.toUTCString();
    },
    get(key:string) {
        var getCookie = document.cookie.replace(/[ ]/g, "");
        var arrCookie = getCookie.split(";");
        var value;
        for (var i = 0; i < arrCookie.length; i++) {
            var arr = arrCookie[i].split("=");
            if (key == arr[0]) {
                value = arr[1];
                break;
            }
        }

        if (value) {
            if (value.charAt(0) == '{' || value.charAt(0) == '[') {
                return JSON.parse(value);
            }
        }
        return value;
    },
    remove(key:string) {
        var date = new Date();
        date.setTime(date.getTime() - 10000);
        document.cookie = key + "=v; expires =" + date.toUTCString();
    }
}